
local SafeFunc = class("SafeFunc")
setmetatable(SafeFunc, {__index = function(tab, key)
    print(string.find(key, "^_"))
    if string.find(key, "^_") == nil then
        print("don't have func = ", key, tab)
        rawset(tab, key, function() end)
        return tab[key]
    end
    return nil
end})

local luaj=nil
local luaoc=nil
local className=nil


if app:isAndroid() then
    luaj= require "cocos.cocos2d.luaj"
    className= "com/repong/framework/ChannelAPI"
elseif app:isIOS() then
    luaoc = require "cocos.cocos2d.luaoc"
    className = "ChannelAPI"
end

local ChannelBase = class("ChannelBase", SafeFunc)

function ChannelBase:ctor()
    self._token = nil
    self._account = nil
    self._loginVerifyed = false
    self._gateHost = nil
    self._sdkCanPay = true
    self:_init()
end

function ChannelBase.callJava(sigs, funName,...)
	assert(sigs,funName)
	local args = {...}
	local ok,ret = luaj.callStaticMethod(className,funName,args,sigs)
	if not ok then
		print("call jni fail ",funName)
	end
	return ok,ret
end

function ChannelBase.callOC(funName,args)
	local ok , ret = luaoc.callStaticMethod(className,funName,args)
	if not ok then
		print("call OC fail ",funName)
	end
	return ok,ret
end

function ChannelBase:getToken()
    return self._token
end

function ChannelBase:getAccount()
    return self._account
end

--
function ChannelBase:isLoginVerifyed()

end

-- 获取网关验证
function ChannelBase:getGateHostFromConfig()
    local redirecturl =  app.configuration:getValue("GameHostRedirecturl")
	if redirecturl and redirecturl ~= "" then
		if string.sub(redirecturl,#redirecturl)~="/" then
			redirecturl = (redirecturl.."/")
		end
		return redirecturl
    end
    
    local gateHosts = app.configuration:getValue("GateHosts") or "login.dev.everadventure.cn:5000/"

    if string.sub(gateHosts,#gateHosts)~="/" then
        gateHosts = (gateHosts.."/")
    end
    -- gateHosts = "http://10.246.89.230:28088/"
    -- gateHosts = "http://10.246.89.6:8088/"
    return gateHosts
end

-- 获取平台
function ChannelBase:getPlatform()
    local targetPlatform = cc.Application:getInstance():getTargetPlatform()
	if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD== targetPlatform) then
		return "ios"
	elseif (cc.PLATFORM_OS_ANDROID == targetPlatform) then
		return "android"
	elseif (cc.PLATFORM_OS_MAC == targetPlatform) then
		return "mac"
	elseif (cc.PLATFORM_OS_WINDOWS == targetPlatform) then
		return "win"
	else
		return "unknow"
	end
end

function ChannelBase:getChannel()
    
end

function ChannelBase:getChannelTag()

end
-- 判断 init
function ChannelBase:isSdkInitSuccess()
    return true
end

function ChannelBase:isLogin()
    return self._isLogin
end


function ChannelBase:_joinUrl(host)
    return host
end

function ChannelBase:gameLogin(cb, newHost)
    local gateHost = self:getGateHostFromConfig()
    local url = self:_joinUrl(gateHost)
    app.session:login(url, nil, cb)
end
-- sdk 登录
function ChannelBase:login(cb)
    self._loginCallback = cb
    self:_login(params)
end

function ChannelBase:logout(cb)
    self._logoutCallback = cb
    self:_logout()
end

function ChannelBase:switchAccount(cb)
    self._switchAccountCallback = cb
    self._switchAccount()
end

--支付
function ChannelBase:pay(cb, ...)
    self._payCallback = cb
    self:_pay(...)
end

function ChannelBase:share(cb, ...)
    self._shareCallback = cb
    self:_share(...)
end

-- 打开用户中心
function ChannelBase:openUserCenter()

end

-- 区服 服务器列表 
function ChannelBase:fetchServerListByPageNum(cb, pageNum, ibegin, iend)
    local url = table.concat({self:getGateHostFromConfig(),"directory?begin=",ibegin,"&end=",iend})
    local account = self:getAccount() or "NONE"
    local channel = self:getChannelId() or ""
    local platform = self:getPlatform() or ""
    url=url.."&account="..account
    url=url.."&channel="..channel
    url=url.."&os="..platform

    
    app.http.reqJsonData(url,function(response,errorMsg,code)
		local message = nil
        local responseType = type(response)
        local data = nil
        if responseType == "table" and response.ret == 0 then
            data = response.data
 		else
 			if responseType == "table" then
 				message = L(response.msg)
 			else
 				message = L(errorMsg)
 			end
        end
        if cb then
        	cb(data,message)
    	end
	end,"GET",true)
end

-- 内网和 msdk 获取 服务器列表 和 登录验证是一个接口
function ChannelBase:fetchServerList(cb)
    self:gameLogin(cb)
end

-- 复写
function ChannelBase:_init()
end

function ChannelBase:_login()

end

function ChannelBase:_logout()

end

function ChannelBase:_switchAccount()

end

function ChannelBase:_pay(payData, customParam)
    self:_onPayFail()
end

function ChannelBase:_share()
    self:_onShareFail()
end

-- --回调
function ChannelBase:_onLoginSuccess(...)
    self._isLogin = true
    if self._loginCallback then
        self._loginCallback(self, "success")
        self._loginCallback = nil
    end
end

function ChannelBase:_onLoginFail(err)
    self._isLogin = false
    if self._loginCallback then
        self._loginCallback(self, "fail", err)
        -- self._loginCallback = nil
    end
end

function ChannelBase:_onLogoutSuccess()
    self._isLogin = false
    if self._logoutCallback then
        self._logoutCallback("success")
        self._logoutCallback = nil
    end
end

function ChannelBase:_onLogoutFail(...)
    if self._logoutCallback then
        self._logoutCallback("fail", ...)
        -- self._logoutCallback = nil
    end
end

function ChannelBase:_onPaySuccess(...)
    if self._payCallback then
        self._payCallback(Enums.PayRetState.success, ...)
        self._payCallback = nil
    end
end


function ChannelBase:_onPayFail(code, ...)
    if self._payCallback then
        if not code then
            code = Enums.PayRetState.fail
        end

        self._payCallback(code, ...)
        -- self._payCallback = nil
    end
end

function ChannelBase:_onShareSuccess(...)
    if self._shareCallback then
        self._shareCallback(false, ...)
        self._shareCallback = nil
    end
end

function ChannelBase:_onShareFail(...)
    if self._shareCallback then
        self._shareCallback(false, ...)
        -- self._shareCallback = nil
    end
end


function ChannelBase:_clonePayGoodsInfo(rechargeGoodsInfo)
    local goods = {}
    for k, v in pairs(rechargeGoodsInfo) do
        local temp = {}
        temp.ID = v.goodsID
        temp.product_id = v.product_id
        temp.price = "US$".. v.price/100 -- 默认是美元（服务器传过来数据是美分）
        temp.showPrice = v.showPrice
        temp.hotGoods = v.hotGoods
        temp.demond = v.demond
        temp.extraGift = v.extraGift
        temp.firstExtraGift = v.firstExtraGift
        temp.firstExtraGiftCD = v.firstExtraGiftCD
        temp.icon = v.icon

        temp.num = v.num
        temp.numType = v.numType
        temp.shopType = v.shopType

        table.insert(goods, temp)
    end
    return goods
end

-- 获取商品列表
function ChannelBase:getPayGoods(cb)
    app.session:request("pb_recharge.C2S_QueryRechargeGoods", {}, function(ret, err)
        if cb then
            local data = {}
            local goods = self:_clonePayGoodsInfo(ret.RechargeGoodsInfos)
            data.RechargeGoodsInfos = goods
            cb("success", data)
        end
    end)
end

function ChannelBase:reqGiftCode(code, cb)
    -- app.session:request("pb_recharge.C2S_UseGiftCode", {}, function(ret)
    --     if cb then
    --         cb(ret)
    --     end
    -- end)
end

function ChannelBase:canPay()
    return self._sdkCanPay
end

-- 是否是提审状态
function ChannelBase:isReview()
    local isAppleReview =  app.configuration:getValue("IsAppleReview")
    return isAppleReview == true
end

-- 设置提审状态
function ChannelBase:setIsReivew(flagIsReview)

end

function ChannelBase:getDeviceId()
    return device.getUdid()
end

-- httpdns
function ChannelBase:getHostByNameAsync(dns, cb)
    if cb then
        executeFunc(cb)
        return
    end
end

function ChannelBase:getServerNameByIndex(serverIndex)
	if not serverIndex then
		return ""
    end
    serverIndex = serverIndex % 1000
	return serverIndex..L("Server")
	
end

return ChannelBase